import { asyncRouterMap, constantRouterMap } from './index'
import {getStorage} from "@/utils/auth";
import * as stn from "@/constants/storeName";

//const menuList = sessionStorage.getItem('menu_list') ? sessionStorage.getItem('menu_list').toLowerCase() : ''
// const menuList = getStorage('menu_list') ? getStorage('menu_list').toLowerCase() : ''
//const menuList = JSON.stringify(getStorage('menu_list'))

// 根据后端返回的所有菜单列表，判断出当前菜单下的哪些子菜单可以浏览，目前仅支持二级菜单
function getChildData(item) {
  if (item.children && item.children.length > 0) {
    var children = []
    item.children.forEach(child => {
      if (navMenu.indexOf(item.path+'/'+child.path) > -1) {
        children.push(child)
        getChildData(child)
      }
    })
    item.children = Object.assign([], children)
  }
}

// 提取后端返回的树形结构菜单的url，生成url集合，用于比对前端route的path
var navMenu = []
function getNavMenu(arr) {
  arr.forEach((item, i) => {
    if (item.children && item.children.length > 0) {
      getNavMenu(item.children)
    }
    navMenu.push(item.url)
  })
}

function navigation(arr, obj) {
  arr.forEach((item, i) => {
    if (item.children && item.children.length > 0) {
      navigation(item.children, obj)
    }
    var str = item.path.replace('/', '')
    if (obj[str]) {
      item.meta.display = 'none'
    }
  })
}

export function asyncRouterData() {
  // const asyncRouterList = Object.assign([], asyncRouterMap)
  //debugger
  getNavMenu(getStorage(stn.MENU_LIST))
  //console.log(navMenu,2222222)
  var dataList = []
  asyncRouterMap.forEach(item => {
    if (navMenu.indexOf(item.path) > -1 || item.path === '*') {
      getChildData(item)
      dataList.push(item)
    }
  })

  //console.log(asyncRouterMap, 'asyncRouterMap')
  //menuList = JSON.stringify(getStorage('menu_list')).toLowerCase()
  /*asyncRouterMap.forEach(item => {
    if (menuList.indexOf(item.path.toLowerCase()) > -1 || item.path === '*') {
      getChildData(item)
      dataList.push(item)
    }
  })*/

  // 菜单去重
  var set = new Set(navMenu)
  var newArr = Array.from(set)
  var obj = {}
  newArr.forEach(i => {
    var array = i.split('/')
    obj[array[array.length - 1]] = 1
  })
  navigation(dataList, obj)
  return dataList
}

export function constantRouterData() {
  getNavMenu(getStorage(stn.MENU_LIST))
  var dataArr = []
  constantRouterMap.forEach(item => {
    if (navMenu.indexOf(item.path) > -1) {
      getChildData(item)
      dataArr.push(item)
    }
  })
  return dataArr
}
